// pages/student/survey/survey.js
const api = require('../../../utils/api')

Page({
  data:{
    headerHeight:0,
    readonly:true,
    grades:['小学','初一','初二','初三','高一','高二','高三'],
    systems:['AP','A-Level','IB','竞赛'],
    subjects:['数学','物理','化学','生物','英语'],
    levels:['基础','一般','良好','优秀'],
    gradeIndex:0, systemIndex:0, subjectIndex:0, levelIndex:0,
    form:{ name:'', gender:1, grade:'', system:'', subject:'', level:'', wish:'' },
    files:[]
  },
  onLoad(options){
    const readonly = String(options && options.readonly) === '1'
    const studentId = options && options.studentId ? options.studentId : ''
    this.setData({ readonly })
    if (studentId){
      this.loadSurvey(studentId)
    } else if (options && options.data){
      // 兜底：本地预览
      let preset = {}
      try{ preset = JSON.parse(decodeURIComponent(options.data)) || {} }catch(e){}
      this.setData({ form: { ...this.data.form, ...preset } })
    }
  },

  async loadSurvey(studentId){
    try{
      const res = await api.survey.getByStudent(studentId)
      if(res && res.success){
        const data = (res.data && res.data.data) || {}
        this.setData({ form: { ...this.data.form, ...(data||{}) } })
      }
    }catch(e){}
  },
  onHeaderReady(e){ this.setData({ headerHeight: e.detail.totalHeight||0 }) },
  onGender(e){ this.setData({ 'form.gender': Number(e.detail.value) }) },
  onGrade(e){ const i=Number(e.detail.value); this.setData({ gradeIndex:i, 'form.grade': this.data.grades[i] }) },
  onSystem(e){ const i=Number(e.detail.value); this.setData({ systemIndex:i, 'form.system': this.data.systems[i] }) },
  onSubject(e){ const i=Number(e.detail.value); this.setData({ subjectIndex:i, 'form.subject': this.data.subjects[i] }) },
  onLevel(e){ const i=Number(e.detail.value); this.setData({ levelIndex:i, 'form.level': this.data.levels[i] }) },
  onUpload(){},
  removeFile(){},
  async onSubmit(){
    try{
      const payload = { teacherId: null, studentId: this.data.form.studentId, data: this.data.form, files: this.data.files }
      const res = await api.survey.save(payload)
      if(res && res.success){ wx.showToast({ title:'已提交', icon:'success' }) }
    }catch(e){ wx.showToast({ title:'提交失败', icon:'none' }) }
  }
})


